﻿using System.Collections;
using System.Collections.Generic;
using KnightWeapons;
using Unity.Netcode;
using UnityEngine;

public class WeaponManager : NetworkBehaviour
{
    public static WeaponManager Instance;
    [SerializeField] GameObject gunPrefab;
    [SerializeField] float offset = 5f;
    List<Vector2> spawnOffset;
    int maxNum = 6;
    int curWeaponNum = 0;

    public Dictionary<int, Bullet> PredictBullets = new();
    public int PredictIdx = 0;

    private void Awake()
    {        
        float x = offset * Mathf.Cos(45), y = offset * Mathf.Sin(45);
        spawnOffset = new()
        {
            new Vector2(x,y),
            new Vector2(offset,0),
            new Vector2(x,-y),
            new Vector2(-x,y),
            new Vector2(-offset,0),
            new Vector2(-x,-y),
        };
    }

    public override void OnNetworkSpawn()
    {
        if (!IsOwner)
            return;
        Instance = this;
        AddWeapon();
    }

    public void AddWeapon()
    {
        OnAddWeaponRpc(OwnerClientId);
    }

    [Rpc(SendTo.Server)]
    void OnAddWeaponRpc(ulong clientId)
    {
        AddWeaponOnServer(clientId);
    }

    public void AddWeaponOnServer(ulong clientId)
    {   
        if (curWeaponNum >= maxNum)
            return;
        var knight = GetComponent<Knight>();
        var weapon = Instantiate(gunPrefab).GetComponent<Gun>();
        weapon.transform.position = knight.Center + spawnOffset[curWeaponNum];
        weapon.NetworkObject.SpawnWithOwnership(clientId,true);
        weapon.NetworkObject.TrySetParent(knight.NetworkObject);
        curWeaponNum++;
    }
}
